package logic

import (
	"context"
	"errors"
	"user_rpc/models"

	"user_rpc/internal/svc"
	"user_rpc/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateUserLogic) CreateUser(in *user.UserInfo) (*user.UserInfo, error) {
	nameUser, err := l.svcCtx.UserModel.FindOneByName(l.ctx, in.Name)
	if err != nil && !errors.Is(err, models.ErrNotFound) {
		l.Logger.Errorf("CreateUser FindOneByName error: %v", err)
		return nil, errors.New("find user by name error")
	}
	if nameUser != nil {
		l.Logger.Errorf("CreateUser FindOneByName error, nameUser: %v", nameUser)
		return nil, errors.New("user name already exists")
	}

	newUser, err := l.svcCtx.UserModel.Insert(l.ctx, &models.User{
		Name:     in.Name,
		Password: in.Password,
	})
	if err != nil {
		l.Logger.Errorf("CreateUser Insert: %v", err)
		return nil, errors.New("insert user error")
	}

	userID, err := newUser.LastInsertId()
	if err != nil {
		l.Logger.Errorf("CreateUser LastInsertId: %v", err)
		return nil, errors.New("insert user then get user_id error")
	}
	return &user.UserInfo{
		Id:       userID,
		Name:     in.Name,
		Password: in.Password,
	}, nil
}
